/**
 * Created by chenyong on 15/11/26.
 * 让IE 10以下的浏览器兼容Web Worker功能
 */

var self;

/**
 * 当浏览器不支持Web Worker时
 * 构造一个BpsWorker对象
 */
if(typeof Worker === 'undefined') {
    Worker = function(worker)
    {
        return new BpsWorker(worker);
    };
}


/**
 * 加载脚本
 * @param src
 */
function importScripts(src)
{
    $.ajax({
        url : src,
        dataType : 'script',
        async : false
    });
}


/**
 * BpsWorker主函数
 * @param worker
 * @constructor
 */
function BpsWorker(worker)
{
    var script = document.createElement('script'),
        func = this,
        num_workers;

    this.ready = true;

    this.queue = [];

    if(typeof BPSWORKER === 'undefined') {
        BPSWORKER = {};
        BPSWORKER.self = self;
        BPSWORKER.workers = [];
    }

    num_workers = BPSWORKER.workers.length;
    BPSWORKER.workers[num_workers] = {};
    this.worker_id = num_workers;
    this.worker_url = worker;


    if(typeof $ !== 'object') {
        this.loadJQuery(function() {
            func.loadWorker();
        });
    }

    func.loadWorker();

    this.onmessage = {};

    BPSWORKER.workers[this.worker_id].postMessage = function(message) { func.returnMessage(message); };
    self = BPSWORKER.workers[this.worker_id];

}


BpsWorker.prototype = {
    /**
     * 使用postmessage函数向worker发送请求
     * @param message
     */
    postMessage : function(message) {
        if(!this.ready) {
            this.queue.push(message);
            return;
        }
        self = BPSWORKER.workers[this.worker_id];
        BPSWORKER.workers[this.worker_id].onmessage({'data' : message});
        self = BPSWORKER.self;
    },


    /**
     * 返回消息
     * @param message
     */
    returnMessage : function(message) {
        this.onmessage({'data' : message});
    },

    /**
     * 加载JQuery
     * @param callback
     */
    loadJQuery : function(callback) {
        this.ready = false;
        var jquery_lib = document.createElement('script');
        jquery_lib.type = 'text/javascript';
        jquery_lib.src = 'http://cdn.bigpixel.cn/libs/jquery/jquery-1.11.3.min.js';
        document.body.appendChild(jquery_lib);
        jquery_lib.onreadystatechange = callback;
        jquery_lib.onload = callback;
    },


    /**
     * 使用Ajax加载工作队列
     * 处理工作队列
     */
    loadWorker : function() {
        this.ready = true;

        var func = this;

        self = BPSWORKER.workers[this.worker_id];
        $.ajax({
            url : func.worker_url,
            dataType : 'script',
            async : false
        });
        self = BPSWORKER.self;

        this.processQueue();
    },

    /**
     * 处理工作队列中的Worker js
     */
    processQueue : function() {
        var queue = this.queue,
            len = queue.length,
            i;

        for(i=0;i<len;i++) {
            this.postMessage(queue[i]);
        }
        this.queue = [];
    }
};